package com.labManage.service.impl;

import com.labManage.dao.BorrowInfoDao;
import com.labManage.dao.GoodsDao;
import com.labManage.dao.KindsDao;
import com.labManage.entity.BorrowInfo;
import com.labManage.entity.Goods;
import com.labManage.entity.User;
import com.labManage.service.GoodService;

import com.labManage.util.BorrowStateUtil;
import com.labManage.util.GoodsStateUtil;
import com.labManage.vo.BorrowHandleState;
import com.labManage.vo.GoodsHandleState;
import com.labManage.vo.GoodsVo;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GoodServiceImpl implements GoodService {

    //service方法需要dao对象来调用对应的dao方法
    @Autowired
    GoodsDao goodsDao;

    @Autowired
    KindsDao kindsDao;

    @Autowired
    BorrowInfoDao borrowInfoDao;

    @Override
    public List<Goods> queryAllGoodsByKindsId(String kindsId) {
        List<Goods> goods = goodsDao.selectAllGoodsByKindsId(kindsId);
        if (null != goods) {
            return goods;
        } else {
            return null;
        }
    }

    @Override
    public List<GoodsVo> queryAllGoods(Integer page, Integer limit, GoodsVo condition, List<Long> kindsIdsList) {
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User) subject.getPrincipal();
        int startIndex = (page - 1) * limit;
        List<Goods> goodsList = goodsDao.selectGoods(startIndex, limit, condition, kindsIdsList);
        List<GoodsVo> goodsVoList = new ArrayList<>();
        if (null != goodsList) {
            for (Goods goods : goodsList) {
                GoodsVo goodsVo = new GoodsVo();
                String kindsName = kindsDao.selectKindsNameByKindsId(goods.getKindsId());
                goodsVo.setId(goods.getId());
                goodsVo.setGoodsName(goods.getGoodsName());
                goodsVo.setGoodsDesc(goods.getGoodsDesc());
                goodsVo.setKindsName(kindsName);
                goodsVo.setGoodsNo(goods.getGoodsNo());
                goodsVo.setGoodsPosition(goods.getGoodsPosition());
                goodsVo.setGoodsState(goods.getGoodsState().trim());
                goodsVo.setCreateTime(goods.getCreateTime());
                goodsVo.setModifyTime(goods.getModifyTime());
                goodsVo.setCreatePerson(goods.getCreatePerson());
                goodsVo.setModifyPerson(goods.getModifyPerson());
                goodsVo.setGoodsNum(goods.getGoodsNum());
                User borrowUser = borrowInfoDao.selectBorrowUserByGoodsId(goods.getId());
                String word = "";
                Boolean needReback = kindsDao.selectKindsNeedRebackByKindsId(goods.getKindsId());
                if (borrowUser == null) {
                    word = GoodsStateUtil.getGoodsButtonWord(goods.getGoodsState(),
                            true,
                            goods.getGoodsHandleState(), needReback);
                } else {
                    word = GoodsStateUtil.getGoodsButtonWord(goods.getGoodsState(),
                            loginUser.getUsername().equals(borrowUser.getUsername()),
                            goods.getGoodsHandleState(), needReback);
                }
                if (word == null) {
                    return null;
                }
                goodsVo.setGoodsButtonWord(word);
                goodsVo.setNeedReback(needReback);
                goodsVo.setHandleState(goods.getGoodsHandleState());
                Boolean selfHandle = false;
                BorrowInfo borrowInfo = borrowInfoDao.selectBorrowInfoByGoodsIdAndBorrowPersonId(goods.getId(), loginUser.getId());
                if (null != borrowInfo) {
                    //4.3、判断登陆人与借阅人是否一致
                    if (loginUser.getId() == borrowInfo.getBorrowPersonId()) {
                        selfHandle = true;
                    } else {
                        selfHandle = false;
                    }
                } else {
                    selfHandle = false;
                }
                Boolean buttonEnable = GoodsStateUtil.getGoodsButtonEnable(needReback, goods.getGoodsHandleState(), selfHandle);
                goodsVo.setButtonEnable(buttonEnable);
                goodsVoList.add(goodsVo);
            }
            return goodsVoList;
        } else {
            return null;
        }
    }

    @Override
    public int deleteGoods(Long id) {
        //1、通过物品id查询物品信息得到物品的状态
        Goods goods = goodsDao.selectGoodsById(id);
        if(goods!=null){
            //2、获取物品操作状态
            String goodsHandleState = goods.getGoodsHandleState();
            //3、根据种类id获取种类名
            Long kindsId = goods.getKindsId();
            String kindsName = kindsDao.selectKindsNameByKindsId(kindsId);
            if(kindsName.equals("耗材类")){
                //4、判断物品类别，如果是耗材类，则借阅信息中不包含借阅操作状态为未同意借阅的即可删除，
                //   且同时删除过期的借阅信息
                List<BorrowInfo> borrowInfos = borrowInfoDao.selectBorrowInfoByGoodsId(id);
                Boolean deleteFlag = true;
                if(borrowInfos!=null){
                    for (BorrowInfo borrowInfo:borrowInfos) {
                        if(false==(borrowInfo.getBorrowHandleState().equals(BorrowHandleState.NOT_NEED_REBACK))){
                            deleteFlag = false;
                            break;
                        }
                    }
                    if(deleteFlag==true){
                        int deleteResult = goodsDao.deleteGoodsById(id);
                        if(deleteResult>0){
                            List<BorrowInfo> borrowInfos1 = borrowInfoDao.selectBorrowInfoByGoodsId(id);
                            if(borrowInfos1.size()==0){
                                return 1;
                            }else{
                                //删除含有该物品的所有借阅信息
                                int deleteBorrowResult = borrowInfoDao.deteteBorrowInfoByGoodsId(id);
                                if(deleteBorrowResult>0){
                                    //删除成功
                                    return 1;
                                }else {
                                    //服务器异常
                                    return 0;
                                }
                            }
                        }else {
                            //服务器异常
                            return 0;
                        }
                    }else {
                        //不能删除，正在被借阅中
                        return 2;
                    }
                }else{
                    //服务器异常
                    return 0;
                }
            }else{
                //5、如果是其他类别，则物品操作状态只能为可借阅方可删除
                if(goodsHandleState.equals(GoodsHandleState.ALLOW_BORROW)){
                    int deleteResult = goodsDao.deleteGoodsById(id);
                    if(deleteResult>0){
                        //删除成功
                        List<BorrowInfo> borrowInfos1 = borrowInfoDao.selectBorrowInfoByGoodsId(id);
                        if(borrowInfos1.size()==0){
                            return 1;
                        }else{
                            //删除含有该物品的所有借阅信息
                            int deleteBorrowResult = borrowInfoDao.deteteBorrowInfoByGoodsId(id);
                            if(deleteBorrowResult>0){
                                //删除成功
                                return 1;
                            }else {
                                //服务器异常
                                return 0;
                            }
                        }
                    }else {
                        //服务器异常
                        return 0;
                    }
                }else {
                    //不能删除，正在被借阅中
                    return 2;
                }
            }
        }else{
            //服务器异常
            return 0;
        }
    }

    @Override
    public long getGoodsNum(GoodsVo condition,List<Long> kindsIdsList) {
        return goodsDao.selectGoodsNum(condition,kindsIdsList);
    }

    @Override
    public long getStoreGoodsNum() {
        return goodsDao.selectStoreGoodsNum();
    }

    @Override
    public int goodsHandleState(Long goodsId, Long selectBorrowNum) {
        //1、根据goodsId查询物品信息
        Goods goods = goodsDao.selectGoodsById(goodsId);
        if (null != goods) {
            //2、获取物品状态和物品操作状态
            String nowGoodsState = goods.getGoodsState();
            String nowGoodsHandleState = goods.getGoodsHandleState();
            //3、根据当前物品状态和物品操作状态，判断是否是正常点击事件访问
            //3.1先查询该物品是否需要归还
            Boolean needReback = kindsDao.selectKindsNeedRebackByKindsId(goods.getKindsId());

            Subject subject = SecurityUtils.getSubject();
            User loginUser = (User) subject.getPrincipal();
            Boolean selfHandle = false;
            BorrowInfo borrowInfo = borrowInfoDao.selectBorrowInfoByGoodsIdAndBorrowPersonId(goods.getId(), loginUser.getId());
            if (null != borrowInfo) {
                //4.3、判断登陆人与借阅人是否一致
                if (loginUser.getId() == borrowInfo.getBorrowPersonId()) {
                    selfHandle = true;
                } else {
                    selfHandle = false;
                }
            } else {
                selfHandle = false;
            }
            Boolean buttonEnable = GoodsStateUtil.getGoodsButtonEnable(needReback, nowGoodsHandleState, selfHandle);

            if (true == buttonEnable) {
                //4 获取物品操作后需要更新的操作状态
                String newGoodsHandleState = GoodsStateUtil.getGoodsHandleStateChanged(needReback, nowGoodsHandleState, selfHandle);
                if (null != newGoodsHandleState) {
                    Goods updateGoods = new Goods();
                    updateGoods.setModifyTime(new Date());
                    updateGoods.setModifyPerson(loginUser.getUsername());
                    updateGoods.setGoodsHandleState(newGoodsHandleState);
                    updateGoods.setId(goodsId);
                    int result1 = goodsDao.updateGoods(updateGoods);
                    if (result1 > 0) {
                        //5、更新该物品借还操作状态
                        String borrowHandleState = GoodsStateUtil.getBorrowHandleStateChanged(needReback, nowGoodsHandleState, selfHandle);
                        if (null != borrowHandleState) {
                            //6、更新借还操作状态、更新/插入借还借还信息（TODO:若为不需要归还的物品，还需要更新借阅信息中的借阅数量）
                            BorrowInfo selectBorrowInfo = borrowInfoDao.selectBorrowInfoByGoodsIdAndBorrowPersonId(goods.getId(), loginUser.getId());
                            if (null != selectBorrowInfo) {
                                //6.1、更新
                                selectBorrowInfo.setModifyTime(new Date());
                                selectBorrowInfo.setModifyPerson(loginUser.getUsername());
                                selectBorrowInfo.setBorrowHandleState(borrowHandleState);
                                if(needReback==true){
                                    selectBorrowInfo.setBorrowNum((long) 0);
                                    selectBorrowInfo.setReturnTime(new Date());
                                }
                                if(needReback==false){
                                    selectBorrowInfo.setBorrowNum(selectBorrowNum);
                                }
                                int updateResult = borrowInfoDao.updateBorrowInfo(selectBorrowInfo);
                                if(0 < updateResult){
                                    if(needReback==false){
                                        BorrowInfo borrowInfo1 = borrowInfoDao.selectBorrowInfoById(selectBorrowInfo.getId());
                                        Goods goods1 = goodsDao.selectGoodsById(goodsId);
                                        if(borrowInfo1.getBorrowNum()>goods1.getGoodsNum()){
                                            return 4;
                                        }else {
                                            return 0;
                                        }
                                    }else{
                                        return 0;
                                    }
                                }else{
                                    //服务器异常
                                    return 3;
                                }
                            } else {
                                //6.2、插入
                                if(selectBorrowNum>goods.getGoodsNum()){
                                    return 4;
                                }
                                BorrowInfo insertBorrowInfo = new BorrowInfo();
                                insertBorrowInfo.setBorrowGoodsId(goodsId);
                                insertBorrowInfo.setBorrowPersonId(loginUser.getId());
                                insertBorrowInfo.setBorrowTime(new Date());
                                insertBorrowInfo.setModifyTime(new Date());
                                insertBorrowInfo.setCreateTime(new Date());
                                insertBorrowInfo.setModifyPerson(loginUser.getUsername());
                                insertBorrowInfo.setCreatePerson(loginUser.getUsername());
                                insertBorrowInfo.setBorrowHandleState(borrowHandleState);
                                insertBorrowInfo.setBorrowNum(selectBorrowNum);
                                int insertResult = borrowInfoDao.insertBorrowInfo(insertBorrowInfo);
                                if (0 < insertResult) {
                                    return 0;
                                } else {
                                    //服务器异常
                                    return 3;
                                }
                            }
                        } else {
                            //非法访问
                            return 2;
                        }
                    } else {
                        //服务器异常
                        return 3;
                    }
                } else {
                    //非法访问
                    return 2;
                }
            } else {
                //非法访问
                return 2;
            }
        } else {
            //物品信息不存在
            return 1;
        }
    }

    @Override
    public int addGoodsInfo(Goods goods) {
        Goods selectGoods = goodsDao.selectGoodsByGoodsNo(goods.getGoodsNo());
        if(selectGoods!=null){
            //物品编号重复
            return 2;
        }
        Boolean needReback = kindsDao.selectKindsNeedRebackByKindsId(goods.getKindsId());

        if(needReback==false){
            if(goods.getGoodsNum()<=0){
                //请输入正确的耗材类数量
                return 4;
            }
        }else{
            if(goods.getGoodsNum()!=1){
                //非耗材类数量必须为1
                return 3;
            }
        }
        goods.setCreateTime(new Date());
        goods.setModifyTime(new Date());
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User) subject.getPrincipal();
        goods.setCreatePerson(loginUser.getUsername());
        goods.setModifyPerson(loginUser.getUsername());
        goods.setGoodsHandleState(GoodsHandleState.ALLOW_BORROW);
        goods.setGoodsState("在库");
        int result = goodsDao.insertGoods(goods);
        //0为服务器异常，1为添加成功
        return result;
    }
}
